package com.zhilianbao.leyaogo.ui.fragment.me.setting;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.events.LeEventCode;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

// 下载的Runnable
public class DownloadRunnable implements Runnable {
    private ProgressDialog pd;
    private static final int REQ_CODE_INSTALL = 200;
    private static final int MSG_WHAT_NET_ERROR = 300;
    private final SettingFragment mSettingFragment;

    public DownloadRunnable(SettingFragment settingFragment, ProgressDialog pd) {
        mSettingFragment = settingFragment;
        this.pd = pd;
    }

    @Override
    public void run() {
        FileOutputStream fos = null;
        InputStream is = null;
        try {
            String downloadURL = "";
            URL url = new URL(downloadURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 连接超时
            conn.setConnectTimeout(5 * 1000);
            // 读取数据超时
            conn.setReadTimeout(5 * 1000);
            // 连接
            conn.connect();
            // 连接成功
            if (conn.getResponseCode() == 200) {
                // 文件的长度
                int max = conn.getContentLength();
                // 设置进度条的最大值
                pd.setMax(max);
                // 下载的文件
                File file = new File(Environment.getExternalStorageDirectory(), "leyaogo.apk");
                // 文件的写出流
                fos = new FileOutputStream(file);
                is = conn.getInputStream();
                int len;
                byte[] buffer = new byte[1024];
                int progress = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    // 当前的进度
                    progress += len;
                    pd.setProgress(progress);
                }
                // 安装
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setDataAndType(Uri.parse("file:" + file.getAbsolutePath()), "application/vnd.android.package-archive");
                // requestCode :请求码,代表是谁发起的请求
                mSettingFragment.startActivityForResult(intent, REQ_CODE_INSTALL);
            } else {
//                handler.sendEmptyMessage(MSG_WHAT_NET_ERROR);
//                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_NET_ERROR));
            }
        } catch (Exception e) {
            e.printStackTrace();
//            handler.sendEmptyMessage(MSG_WHAT_NET_ERROR);
//            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_NET_ERROR));
        } finally {
            // 关流
            try {
                is.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
//    private Handler handler = new Handler() {
//        public void handleMessage(android.os.Message msg) {
//            switch (msg.what) {
//                case MSG_WHAT_NET_ERROR:
//                    Toast.makeText(mSettingFragment.getContext(), "网络连接失败,请参考错误码300", Toast.LENGTH_SHORT).show();
//                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SWICH_TO_HOME));
//                    mSettingFragment.getActivity().finish();
//                    break;
//            }
//        }
//    };
}
